package com.bleet.securitysms;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ChangePwd extends Activity implements OnClickListener{
	private EditText newPwd, confirmPwd, oldPwd;
	private Button update;
	
	private SharedPreferences prefsPrivate;
	public static final String PREFS_PRIVATE = "PREFS_PRIVATE";
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.changepwd);
        setupViews();
    }

	private void setupViews() {
		newPwd = (EditText) findViewById(R.id.newpassword);
		confirmPwd = (EditText) findViewById(R.id.confirmpass);
		oldPwd = (EditText) findViewById(R.id.oldpassword);
		update = (Button) findViewById(R.id.update);
		update.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		String old = oldPwd.getText().toString();
		if(SettingStatus.getPassword(this).equals(Security.toMd5(old.getBytes()))){
			createPwd(newPwd.getText().toString(), confirmPwd.getText().toString());
		}else {
			Toast.makeText(this, getResources().getString(R.string.update_wrongpassword), Toast.LENGTH_LONG).show();
		}
	}
	
	private void createPwd(String firstPwd, String confirmPwd){
		if(firstPwd.matches("[0-9a-zA-Z]{6,8}")){
			if(confirmPwd.matches("[0-9a-zA-Z]{6,8}")){
				if (firstPwd.equals(confirmPwd)) {
					prefsPrivate = getSharedPreferences(PREFS_PRIVATE, Context.MODE_PRIVATE);
					Editor prefsPrivateEditor = prefsPrivate.edit();
					prefsPrivateEditor.putString("password", Security.toMd5(firstPwd.getBytes()));
					prefsPrivateEditor.putBoolean("createdpwd", true);
					prefsPrivateEditor.commit();
//					SettingStatus.password = Security.toMd5(firstPwd.getBytes());
//					SettingStatus.createdpwd = true;
					Toast.makeText(this,getResources().getString(R.string.updatepwdsuccess),Toast.LENGTH_LONG).show();
					Intent intent = new Intent(this, Input.class);
					startActivity(intent);
					finish();
				} else {
					Toast.makeText(this,getResources().getString(R.string.update_inputpwdagain),Toast.LENGTH_LONG).show();
				}
			}else {
				Toast.makeText(this,getResources().getString(R.string.passwordformaterror),Toast.LENGTH_LONG).show();
			}
		}else {
			Toast.makeText(this,getResources().getString(R.string.passwordformaterror),Toast.LENGTH_LONG).show();
		}
	}
}
